console.log('保存新增: => ', $event);
const apiPage = this.getApiPage();
const variables = this.pageObj.getVariables();
const $form = apiPage.getApiWidgetByAliasName('edit-form')?.widgetObj;
const $list = apiPage.getApiWidgetByAliasName('新增演练人员')?.widgetObj;
const gis = apiPage.getApiWidgetByAliasName('三维组件')?.widgetObj;
const edits = apiPage.getApiWidgetsByClassName('edit');
const projects = apiPage.getDataById('848159656336424960')?.data || [];
const levels = apiPage.getDataById('744574925553008640')?.data || [];
const types = apiPage.getDataById('744575296061046784')?.data || [];
const eventNatures = apiPage.getDataById('756194853578080256')?.data || [];
const sourceSystem = apiPage.getDataById('800764940934709248')?.data || [];
const prefix = variables.find(v => v.name === "environmentType")?.value;


const reloadDrillList = () => {
  const panel = this.pageObj.getApiWidgetByAliasName('event-panel')?.widgetObj;
  const queryManage = this.pageObj.getApiWidgetByAliasName('queryManage')?.widgetObj;
  const type = variables.find(v => v.name === 'panelType')?.value || 0;
  const process = variables.find(v => v.name === 'whetherProcess')?.value || 0;
  const searchText = variables.find(v => v.name === 'searchText')?.value;

  apiPage.setVariables([{ name: 'searchText', value: searchText }]);
  apiPage.setVariables([{ name: 'event_type', value: type }]);

  if (+type === 0) {
    queryManage.queryDrillNews(process, searchText).then(res => {
      panel.setData([{data: res}]);
      panel.render()
    })
  } else {
    queryManage.queryDrillGroup(type, process).then(res => {
      panel.setData([{data: res}]);
      panel.render()
    })
  }
};

const requestDrill = (url, body) => {
  const options = {
    method: 'POST',
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body)
  };
  return fetch(url, options).then(res => res.json()).then(res => {
    // 刷新列表
    reloadDrillList();
    return res
  })
};

function addDrill(dataSource) {
  console.log('save', dataSource);
  requestDrill(`/${prefix}Event/drillPlanInfo/insert`, dataSource).then(({ success }) => {
    if (success) {
      $list?.hide();
      layer?.msg('新增演练成功!');

      edits?.forEach(v => v.hideWidget());
      gis?.setIconPosition({ right: 20, top: 100 });
      gis?.setModalPosition({ right: 405, bottom: 20, maxWidth: 1510, width: 810, height: 286, maxHeight: 960 });
      gis?.gisMap.showOrHideAllArea(false);
      apiPage.setVariables([{ name: 'update', value: new Date().toLocaleTimeString() }]);
      console.log("新增演练成功_123")
    }
  });
}

function updateDrill(dataSource) {
  requestDrill(`/${prefix}Event/drillPlanInfo/update`, dataSource).then(({ success }) => {
    if (success) {
      $list?.hide();
      layer?.msg('变更演练成功!');
      console.log("变更演练成功_123，跳转到启动方案页面！");

      edits?.forEach(v => v.hideWidget());
      gis?.setIconPosition({ right: 20, top: 100 });
      gis?.setModalPosition({ right: 405, bottom: 20, maxWidth: 1510, width: 810, height: 286, maxHeight: 960 });
      gis?.gisMap.showOrHideAllArea(false);
      apiPage.setVariables([{ name: 'update', value: data.id }]);
      // 跳转到启动方案页面！
      window.parent.postMessage({ type: 'nav/style', pageName: '演练' }, document.referrer);
      apiPage.navigateStage('843567423519981568', [{ name: 'screen_params', value: data }]);
    }
  });
}

if ($form) {
  layui.form.submit($form._option.instanceName, (form) => {
    let dataSource = Object.entries(form.field).reduce((def, [key, value]) => value !== '' ? (def[key] = value, def) : def, {});
    const type = types.find(v => v.value === dataSource.eventTypeCode);
    const level = levels.find(v => v.value === dataSource.eventGradeCode);
    const quality = eventNatures.find(v => v.value === dataSource.eventQualityCode);
    const project = projects?.find(v => v.value === dataSource.projectCode);
    const [ startTime, endTime ] = dataSource.drillDatetimeRange?.split(' - ') || [];

    // 演练名称
    if (dataSource.drillName?.trim().length > 50) return layer?.msg('演练名称请保持50字以内');
    // 演练范围
    if (dataSource.eventRange?.trim().length > 500) return layer?.msg('演练范围请保持500字以内');
    // 周边环境
    if (dataSource.eventEnvironment?.trim().length > 500) return layer?.msg('周边环境请保持500字以内');
    // 演练目的
    if (dataSource.drillSake?.trim().length > 500) return layer?.msg('演练目的请保持500字以内');
    // 演练内容
    if (dataSource.drillContent?.trim().length > 5000) return layer?.msg('演练内容请保持5000字以内');

    const body = {
      // 演练来源
      projectName: project.name,
      projectCode: project.value,
      projectId: project.id,
      // 演练状态(0-未演练；2-演练中；1-已演练)
      disableFlag: 0,
      // 演练内容
      drillContent: dataSource.drillContent,
      // 演练区域
      drillLocation: dataSource?.drillLocation,
      // 演练区域id
      drillLocationId: dataSource?.drillLocationId,
      // 演练名称
      drillName: dataSource.drillName,
      // 演练组织典信息
      // drillPersonInfoDictTreeNodes: [],
      // 演练目的
      drillSake: dataSource.drillSake,
      // 事件周边环境
      eventEnvironment: dataSource.eventEnvironment,
      // 事件等级
      eventGrade: level?.name,
      // 事件等级编码
      eventGradeCode: level?.value,
      // 事件性质
      eventQuality: quality?.name,
      // 事件性质编码
      eventQualityCode: quality?.value,
      // 事件影响范围
      eventRange: dataSource.eventRange,
      // 事件类型
      eventType: type?.name,
      // 事件类型编码
      eventTypeCode: type?.value,
      // 点位id
      pointId: '', // dataSource.eventPoint,
      // 点位名称
      pointName: '',
      // 事件来源
      source: sourceSystem.find(v => v.value === dataSource.source)?.name,
      // 演练开始时间
      startTime: startTime,
      // 演练结束时间
      endTime: endTime,

      xcoordinate: dataSource.xCoordinate,
      ycoordinate: dataSource.yCoordinate,
      zcoordinate: dataSource.zCoordinate,

      eventDetails: void 0
    };

    if ($list) {
      const Modal = $list.getModal();
      if (Modal.submitData?.length) {
        // 演练组织典信息
        body.drillPersonInfoDictTreeNodes = Modal.filterDataSource(Modal.submitData);
      }
    }

    console.log('onModalSubmitClick', form, dataSource);
    if (dataSource.thumbnailPath || dataSource.jpbPath) {
      const eventDetails = {};
      if (dataSource.thumbnailPath) eventDetails.thumbnailPath = dataSource.thumbnailPath;
      if (dataSource.jpbPath) eventDetails.jpbPath = dataSource.jpbPath;
      body.eventDetails = JSON.stringify(eventDetails);
    }

    if (dataSource.id) {
      let params = variables.find(v => v.name === "screen_params")?.value;

      if (params) {
        try {
          params = JSON.parse(params);

          body.id = dataSource.id || params.id;
          body.disableFlag = -2;
          updateDrill(body)
        } catch (e) {
          console.error(e)
        }
      }
    } else {
      addDrill(body)
    }
  });
}